<template>
  <div class="login-container">
    <el-row>
      <el-col :xs="24" :sm="24" :md="12" :lg="15" :xl="15">
        <img
          alt=""
          class="login-image"
          src="@/assets/login_images/background.png"
        />
      </el-col>
      <el-col
        :xs="24"
        :sm="24"
        :md="12"
        :lg="9"
        :xl="9"
        style="text-align: center"
      >
        <el-form
          ref="form"
          :model="form"
          :rules="rules"
          class="login-form"
          label-position="left"
        >
          <div class="title-tips">欢迎登陆！</div>
          <el-form-item style="margin-top: 20px" prop="username">
            <el-input
              v-model.trim="form.username"
              v-focus
              placeholder="请输入用户名"
              tabindex="1"
              type="text"
            />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              :key="passwordType"
              ref="password"
              v-model.trim="form.password"
              :type="passwordType"
              tabindex="2"
              placeholder="请输入密码"
              @keyup.enter.native="handleLogin"
            />
            <span
              v-if="passwordType === 'password'"
              class="show-password"
              @click="handlePassword"
            >
              <vab-icon :icon="['fas', 'eye-slash']"></vab-icon>
            </span>
            <span v-else class="show-password" @click="handlePassword">
              <vab-icon :icon="['fas', 'eye']"></vab-icon>
            </span>
          </el-form-item>
          <el-form-item prop="slider" class="slider">
            <div>
              <div v-loading="spinShow" class="panel">
                <div class="slider-img">
                  <img class="slider-bg-img" :src="sliderBgimg" />
                  <img
                    class="slider-block-img"
                    :style="{ left: blockLeft + 'px' }"
                    :src="sliderBlockImg"
                    @mousedown="onMousedown"
                  />
                </div>
                <i
                  v-if="!refreshShow"
                  style="
                    color: #fff;
                    font-size: 20px;
                    position: absolute;
                    right: 5px;
                    top: 5px;
                    cursor: pointer;
                  "
                  class="el-icon-refresh"
                  @click="refreshImg"
                />
              </div>
              <div
                class="control"
                style="
                  position: relative;
                  background-color: #f6f4fc;
                  height: 42px;
                "
              >
                <div
                  class="slide-indicator"
                  :style="{ width: blockLeft + 'px' }"
                  :class="[
                    isActive ? indicatorActiveClass : '',
                    isSuccess ? indicatorSuccessClass : '',
                    isError ? indicatorErrorClass : '',
                  ]"
                  style="height: 40px; position: absolute"
                ></div>
                <div
                  class="slider-block"
                  :style="{ left: blockLeft + 'px' }"
                  :class="[canDrag ? canDragClass : canNotDragClass]"
                  style="
                    position: absolute;
                    height: 40px;
                    width: 40px;
                    background-color: #fff;
                    box-shadow: 0 0 3px rgba(0, 0, 0, 0.3);
                  "
                  @mousedown="onMousedown"
                >
                  <i
                    class="el-icon-right slider-block-icon"
                    :class="[
                      isReady ? readyClass : '',
                      isActive ? activeClass : '',
                      isSuccess ? successClass : '',
                      isError ? errorClass : '',
                    ]"
                    style="
                      width: 40px;
                      text-align: center;
                      font-size: 18px;
                      height: 40px;
                      line-height: 40px;
                      font-weight: bold;
                    "
                  />
                </div>
                <div
                  class="slider-tips"
                  style="line-height: 42px; text-align: center; font-size: 14px"
                >
                  <span class="slider-tips-text">{{ tips }}</span>
                </div>
              </div>
            </div>
            <div
              v-if="showDragTime"
              class="drag-time"
              style="
                width: 100%;
                position: absolute;
                bottom: 37px;
                z-index: 96;
                text-align: center;
                color: #429bed;
              "
            >
              {{ showDragTimeMsg }}
            </div>
          </el-form-item>
          <el-button
            :loading="loading"
            class="login-btn"
            type="primary"
            @click="handleLogin"
          >
            登录
          </el-button>
          <!-- <router-link to="/register">
            <div style="margin-top: 20px">注册</div>
          </router-link> -->
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
  import { isPassword } from '@/utils/validate'

  export default {
    name: 'Login',
    directives: {
      focus: {
        inserted(el) {
          el.querySelector('input').focus()
        },
      },
    },
    data() {
      const validateusername = (rule, value, callback) => {
        if ('' == value) {
          callback(new Error('用户名不能为空'))
        } else {
          callback()
        }
      }
      const validatePassword = (rule, value, callback) => {
        if (!isPassword(value)) {
          callback(new Error('密码不能少于6位'))
        } else {
          callback()
        }
      }
      return {
        isShowPassword: false,
        showPasswordType: 'ios-eye-off',
        inputPasswordType: 'password',
        isVerify: true,
        serialNumber: null,
        sliderBgimg:
          'http://necaptcha.nosdn.127.net/130433f994b546059bbba5098ecaae50.jpg',
        sliderBlockImg:
          'http://necaptcha.nosdn.127.net/c9ad802513234f1083d44f70a63ec0a6.png',
        spinShow: false, // 是否显示图片加载中
        refreshShow: false, // 是否显示刷新按钮
        blockLeft: 0, // 移动距离
        width: 278, // 滑动总宽度
        startClientX: 0, // 开始滑动x位置
        nowClientX: 0, // 当前滑块x位置
        canDrag: true, // 是否可以滑动
        isReady: true, // 是否准备好
        isActive: false, // 是否在滑动中
        isSuccess: false, // 是否成功
        isError: false, // 是否失败
        readyClass: 'ready-block', // 滑块初始样式
        activeClass: 'active-block', // 滑块滑动中样式
        successClass: 'success-block', // 验证成功滑块样式
        errorClass: 'error-block', // 验证失败滑块样式
        indicatorActiveClass: 'active-indicator', // 滑块滑动中滑过区域的样式
        indicatorSuccessClass: 'success-indicator', // 验证失败滑块滑过区域的样式
        indicatorErrorClass: 'error-indicator', // 验证失败滑块滑过的区域的样式
        iconType: 'ios-arrow-round-forward', // 滑块中图标的样式
        tips: '向右拖动滑块填充拼图', // 提示文字
        canDragClass: 'can-drag',
        canNotDragClass: 'can-not-drag',
        showDragTime: false,
        dragTimeInterval: null,
        dragTime: 0.01,
        showDragTimeMsg: '',
        nodeEnv: process.env.NODE_ENV,
        title: this.$baseTitle,
        form: {
          username: '',
          password: '',
        },
        rules: {
          username: [
            {
              required: true,
              trigger: 'blur',
              validator: validateusername,
            },
          ],
          password: [
            {
              required: true,
              trigger: 'blur',
              validator: validatePassword,
            },
          ],
        },
        loading: false,
        passwordType: 'password',
        redirect: undefined,
      }
    },
    watch: {
      $route: {
        handler(route) {
          this.redirect = (route.query && route.query.redirect) || '/'
        },
        immediate: true,
      },
    },
    created() {
      document.body.style.overflow = 'hidden'
      // this.slideImage()
    },
    beforeDestroy() {
      document.body.style.overflow = 'auto'
    },
    mounted() {
      this.form.username = 'admin'
      this.form.password = '123456'
      // setTimeout(() => {
      //   this.handleLogin()
      // }, 3000)
    },
    methods: {
      slideImage() {
        this.canDrag = false
        this.refreshShow = false
        this.spinShow = true
        getSlideImage().then((res) => {
          this.sliderBlockImg = res.data.smallImgName
          this.sliderBgimg = res.data.bigImgName
          this.serialNumber = res.data.serialNumber
          this.canDrag = true
          this.spinShow = false
          this.refreshShow = true
          this.iconType = 'ios-arrow-round-forward'
          this.blockLeft = 0
          this.tips = '向右拖动滑块填充拼图'
          this.isActive = false
          this.isSuccess = false
          this.isError = false
          this.isReady = true
        })
      },
      refreshImg() {
        this.slideImage()
      },
      handleSubmit() {
        this.$refs.loginForm.validate((valid) => {
          if (valid) {
            this.$emit('on-success-valid', {
              username: this.form.userName,
              password: this.form.password,
              serialNumber: this.serialNumber,
              blockLeft: this.blockLeft,
            })
            this.isVerify = true
          }
        })
      },
      onMousedown: function (e) {
        let _t = this
        this.dragTime = 0
        if (!this.canDrag) {
          return
        }
        this.dragTimeInterval = setInterval(function () {
          _t.dragTime += 0.01
        }, 10)
        e.preventDefault()
        this.isActive = true
        this.startClientX = e.clientX
        if (document.addEventListener) {
          window.addEventListener('mousemove', this.onPointerDrag, false)
          window.addEventListener('mouseup', this.onPointerDragEnd, false)
        } else {
          window.attachEvent('onmousemove', this.onPointerDrag)
          window.attachEvent('onmouseup', this.onPointerDragEnd)
        }
      },
      onPointerDrag: function (e) {
        if (!this.canDrag) {
          return
        }
        this.tips = ''
        this.nowClientX = e.clientX
        let clientX = this.nowClientX - this.startClientX
        if (clientX >= 0 && clientX <= this.width) {
          this.blockLeft = clientX
        }
      },
      onPointerDragEnd: function (e) {
        let _t = this
        if (this.dragTimeInterval) {
          clearInterval(this.dragTimeInterval['_id'])
        }
        if (document.addEventListener) {
          window.removeEventListener('mousemove', this.onPointerDrag)
          window.removeEventListener('mouseup', this.onPointerDragEnd)
        } else {
          window.detachEvent('onmousemove', this.onPointerDrag)
          window.detachEvent('onmouseup', this.onPointerDragEnd)
        }
        let params = {
          serialNumber: this.serialNumber,
          blockLeft: this.blockLeft,
        }
        slideImageAuthenticator(params).then((res) => {
          if (res.code === 200) {
            _t.showDragTime = true
            _t.showDragTimeMsg =
              '只用了' + _t.dragTime.toFixed(2) + '秒,简直比闪电还快'
            _t.isVerify = false
            _t.canDrag = false
            _t.refreshShow = false
            _t.isSuccess = true
            _t.iconType = 'ios-checkmark'
            setTimeout(function () {
              _t.showDragTime = false
            }, 1500)
          } else {
            _t.canDrag = false
            _t.isError = true
            _t.iconType = 'ios-close'
            _t.refreshShow = true
            setTimeout(() => {
              _t.blockLeft = 0
              _t.isError = false
              _t.isActive = false
              _t.iconType = 'ios-arrow-round-forward'
              _t.tips = '加载中...'
              getSlideImage().then((res) => {
                _t.sliderBlockImg = res.data.smallImgName
                _t.sliderBgimg = res.data.bigImgName
                this.serialNumber = res.data.serialNumber
                _t.canDrag = true
                _t.spinShow = false
                _t.refreshShow = true
                _t.tips = '向右拖动滑块填充拼图'
                _t.isError = false
                _t.isSuccess = false
                _t.isReady = true
              })
            }, 1000)
          }
        })
      },
      showPassword() {
        this.isShowPassword = !this.isShowPassword
        if (this.isShowPassword) {
          this.showPasswordType = 'ios-eye'
          this.inputPasswordType = 'text'
        } else {
          this.showPasswordType = 'ios-eye-off'
          this.inputPasswordType = 'password'
        }
      },
      onChange() {
        if (this.isVerify) {
          this.isVerify = false
        }
      },
      handlePassword() {
        this.passwordType === 'password'
          ? (this.passwordType = '')
          : (this.passwordType = 'password')
        this.$nextTick(() => {
          this.$refs.password.focus()
        })
      },
      handleLogin() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.loading = true
            this.$store
              .dispatch('user/login', this.form)
              .then(() => {
                const routerPath =
                  this.redirect === '/404' || this.redirect === '/401'
                    ? '/'
                    : this.redirect
                this.$router.push(routerPath).catch(() => {})
                this.loading = false
              })
              .catch(() => {
                this.loading = false
              })
          } else {
            return false
          }
        })
      },
    },
  }
</script>

<style lang="scss" scoped>
  .login-container {
    height: 100vh;
    background-color: #ffffff;
    .login-image {
      margin: calc((100vh - 520px) / 2) 10% 10%;
      height: 520px;
    }
    .el-form-item {
      border: none !important;
    }
    .title {
      font-size: 54px;
      font-weight: 500;
      color: rgba(14, 18, 26, 1);
    }

    .title-tips {
      font-size: 26px;
      font-weight: 400;
      color: rgba(14, 18, 26, 1);
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    .login-btn {
      display: inherit;
      width: 320px;
      height: 44px;
      margin-top: 5px;
      border: 0;

      &:hover {
        opacity: 0.9;
      }
    }

    .slider {
      .panel {
        height: 180px;
        position: relative;
        .slider-img {
          position: absolute;
          .slider-bg-img {
            position: absolute;
          }
          .slider-block-img {
            position: absolute;
            top: 1px;
          }
        }
      }
      .control {
        .can-drag {
          cursor: move;
        }
        .can-not-drag {
          cursor: not-allowed;
        }
        .active-indicator {
          border: 1px solid #abdcff;
          border-right: none;
          background-color: #f0faff;
        }
        .success-indicator {
          border: 1px solid #8ce6b0;
          border-right: none;
          background-color: #edfff3;
        }
        .error-indicator {
          border: 1px solid #ffb08f;
          border-right: none;
          background-color: #ffefe6;
        }
        .slider-block {
          .ready-block {
            background-color: #fff;
            color: #515a6e;
          }
          .active-block {
            background-color: #429bed;
            color: #fff;
          }
          .success-block {
            background-color: #429bed;
            color: #fff;
          }
          .error-block {
            background-color: #ed4014;
            color: #fff;
          }
        }
      }
    }
    .login-form {
      position: relative;
      width: 320px;
      margin: calc((100vh - 520px) / 2) 10% 10%;
      overflow: hidden;

      .forget-password {
        width: 100%;
        margin-top: 40px;
        text-align: left;

        .forget-pass {
          width: 129px;
          height: 19px;
          font-size: 20px;
          font-weight: 400;
          color: rgba(92, 102, 240, 1);
        }
      }
    }

    .tips {
      margin-bottom: 10px;
      font-size: $base-font-size-default;
      color: $base-color-white;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .title-container {
      position: relative;

      .title {
        margin: 0 auto 40px auto;
        font-size: 34px;
        font-weight: bold;
        color: $base-color-blue;
        text-align: center;
      }
    }

    .svg-container {
      position: absolute;
      top: 14px;
      left: 15px;
      z-index: $base-z-index;
      font-size: 16px;
      color: #d7dee3;
      cursor: pointer;
      user-select: none;
    }

    .show-password {
      position: absolute;
      top: 14px;
      right: 25px;
      font-size: 16px;
      color: #d7dee3;
      cursor: pointer;
      user-select: none;
    }

    ::v-deep {
      .el-form-item {
        padding-right: 0;
        margin: 20px 0;
        color: #454545;
        background: transparent;
        border: 1px solid transparent;
        border-radius: 2px;

        &__content {
          min-height: $base-input-height;
          line-height: $base-input-height;
        }

        &__error {
          position: absolute;
          top: 100%;
          left: 18px;
          font-size: $base-font-size-small;
          line-height: 18px;
          color: $base-color-red;
        }
      }

      .el-input {
        box-sizing: border-box;

        input {
          height: 44px;
          padding-left: 15px;
          font-size: $base-font-size-default;
          line-height: 44px;
          color: $base-font-color;
          background: #f6f4fc;
          border: 0;
          caret-color: $base-font-color;
        }
      }
    }
  }
</style>
